package com.firstclass.interceptor;


import cn.hutool.core.util.StrUtil;
import com.firstclass.exception.BadRequestException;
import com.firstclass.service.UserService;
import com.firstclass.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 */
public class UserInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        final String method = request.getMethod();
        if (HttpMethod.OPTIONS.toString().equals(method)) {
            return true;
        }
        final String token = TokenUtils.getToken(request);
        if (StrUtil.isBlank(token)) {
            throw new BadRequestException("token 不存在");
        }
        final Integer id = Integer.parseInt(TokenUtils.parseToken(token));
        if (userService.getById(id) == null) {
            throw new BadRequestException("无效 token");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
